from flask import render_template, redirect, url_for, flash, request
from flask_login import current_user, login_required
from app import db
from app.skills import bp
from app.skills.forms import SkillForm
from app.models import Skill, User
from app.decorators import admin_required

@bp.route('/')
@login_required
def index():
    skills = Skill.query.all()
    return render_template('skills/index.html', title='技能列表', skills=skills)

@bp.route('/create', methods=['GET', 'POST'])
@login_required
@admin_required
def create():
    form = SkillForm()
    if form.validate_on_submit():
        skill = Skill(name=form.name.data)
        db.session.add(skill)
        db.session.commit()
        flash('技能标签已创建！')
        return redirect(url_for('skills.index'))
    return render_template('skills/create.html', title='创建技能标签', form=form)

@bp.route('/<int:skill_id>/edit', methods=['GET', 'POST'])
@login_required
@admin_required
def edit(skill_id):
    skill = Skill.query.get_or_404(skill_id)
    form = SkillForm(obj=skill)
    if form.validate_on_submit():
        skill.name = form.name.data
        db.session.commit()
        flash('技能标签已更新！')
        return redirect(url_for('skills.index'))
    return render_template('skills/edit.html', title='编辑技能标签', form=form, skill=skill)

@bp.route('/<int:skill_id>/delete')
@login_required
@admin_required
def delete(skill_id):
    skill = Skill.query.get_or_404(skill_id)
    db.session.delete(skill)
    db.session.commit()
    flash('技能标签已删除！')
    return redirect(url_for('skills.index'))

@bp.route('/<int:skill_id>/users')
@login_required
def users(skill_id):
    skill = Skill.query.get_or_404(skill_id)
    return render_template('skills/users.html', title=f'拥有{skill.name}技能的成员', skill=skill)